package com.yly.common.response;

import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Objects;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;


/**
 * @author anqinghang
 */
@Service
public class ResponseConverter {

  /**
   * 返回空的 200状态码
   *
   * @param <T> 类型
   * @return 结构体
   */
  public <T> ResponseVO<T> convert() {
    ResponseVO<T> result = new ResponseVO<>();
    result.setCode(HttpStatus.OK.value());
    result.setMessage("success");
    return result;
  }

  public <T> ResponseVO<T> convert(T data) {
    ResponseVO<T> result = new ResponseVO<>();
    result.setCode(HttpStatus.OK.value());
    result.setData(data);
    result.setMessage("success");
    if (data == null) {
      result.setTotal(0L);
    } else {
      long length = 1L;
      if (data.getClass().isArray()) {
        length = Array.getLength(data);
      }
      if (data instanceof Collection) {
        length = ((Collection<?>) data).size();
      }
      result.setTotal(length);

      result.setCurrentPage(0L);
    }

    return result;
  }

  public <T> ResponseVO<T> convert(T data, Long total) {
    ResponseVO<T> result = new ResponseVO<>();
    result.setCode(HttpStatus.OK.value());
    result.setData(data);
    result.setMessage("success");
    if (total != null) {
      result.setTotal(total);
      result.setCurrentPage(0L);
    }
    return result;
  }

  public <T> ResponseVO<T> convert(T data, Long total, Long currentPage) {
    ResponseVO<T> result = new ResponseVO<>();
    result.setCode(HttpStatus.OK.value());
    result.setData(data);
    result.setMessage("success");
    result.setTotal(Objects.requireNonNullElse(total, 0L));
    result.setCurrentPage(Objects.requireNonNullElse(currentPage, 0L));
    return result;
  }

  public <T> ResponseVO<T> convert(int status, String message) {
    ResponseVO<T> result = new ResponseVO<>();
    result.setCode(status);
    result.setMessage(message);
    return result;
  }

  public <T> ResponseVO<T> convert(ServiceException e) {
    ResponseVO<T> result = new ResponseVO<>();
    result.setCode(e.getStatus().value());
    result.setMessage(e.getMessage());
    return result;
  }

  public <T> ResponseVO<T> convert(Exception e) {
    ResponseVO<T> result = new ResponseVO<>();
    result.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
    result.setMessage(e.getMessage());
    return result;
  }

}
